package com.kizuki.thread;

import org.junit.Test;

public class ProducerConsumer01 {

    @Test
    public void TestSynchronizedPC(){
        Data data = new Data();

        new Thread(()->{
            for (int i  = 0; i < 5; i ++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生产者").start();

        new Thread(()->{
            for (int i  = 0; i < 20; i ++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者").start();

        new Thread(()->{
            for (int i  = 0; i < 15; i ++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生产者2").start();
    }
}

// 判断条件->业务->通知
class Data {
    private int number = 0;

    // notifyAll 之后现成继续从wait()方法之后执行
    // 用while替代if 防止虚假唤醒的情况 即唤醒后需要再次判断条件才能执行加减操作
    public synchronized void add() throws InterruptedException {
        while (number != 0) {
            this.wait();
        }
        System.out.println(Thread.currentThread().getName() + "生产了data 此时number = " + (++number));
        this.notifyAll();
    }

    public synchronized void dec() throws InterruptedException {
        while (number == 0) {
            this.wait();
        }
        System.out.println(Thread.currentThread().getName() + "消费了data 此时number = " + (--number));
        this.notifyAll();
    }

}
